package controllers;

import java.io.File;
import play.*;
import play.libs.F.*;
import play.libs.*;
import play.mvc.*;
import play.cache.Cache;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.util.*;
import models.*;

import weibo4j.Oauth;
import weibo4j.Timeline;
import weibo4j.model.Status;
import weibo4j.model.WeiboException;
import weibo4j.http.AccessToken;

public class Application extends Controller {
    private static User currentUser;


    @Before(unless = {"index", "login", "register", "dealRegister","captcha"})
    private static void checkAuth() {
        if (session.get("usr") == null) {
            index();
        }
    }

    @Before(unless = {"index", "login", "register", "dealRegister","captcha"})
    private static void setupCurrentUser(){
        currentUser = getUser();
    }
    protected static User getUser() {
        return User.findById(getUserId());
    }

    protected static long getUserId() {

        return Long.parseLong(session.get("usr"));
    }

    public static void index() {
        if (session.get("usr") == null) {
            render("Application/login.html");
        } else {
                 
            show(Long.parseLong(session.get("usr")));
        }
    }

    public static void follow(long id) {
        User usr = getUser();
        User usr_to_follow = User.findById(id);
        if (Follow.find("byFromWhoAndToWho", usr, usr_to_follow).first() == null) {
            new Follow(usr, usr_to_follow).save();
            usr.followingCnt++;
            usr_to_follow.followersCnt++;
            usr.save();
            usr_to_follow.save();
        }
   
        //通知用户有新粉丝
        Notify  inform = Notify.getNotifyById(id);
        inform.publishFansEvent(usr); 
        System.out.println("OKKKKKK");
    }
   public static void getNewFans(){
       System.out.println("ooops");
       Notify myNotify = Notify.getNotifyById( getUserId() );
       List<IndexedEvent<User>> newFans = await(myNotify.getFansEvents());
       myNotify.deleteFansEvents();
       renderJSON(newFans);
   }


    public static void unfollow(long id) {
        System.out.println("uuuuuu2222222222222222222");
        User usr = getUser();
        usr.followingCnt--;
        User usr_to_follow = User.findById(id);
        usr_to_follow.followersCnt--;
        usr.save();
        usr_to_follow.save();
        System.out.println("uuuuuubbbbbbbbbbbbbbbbbbb");
        MBlog.find("byAuthor", usr).fetch();
        Follow relation = Follow.find("byFromWhoAndToWho", usr, usr_to_follow).first();
        relation.delete();
        System.out.println("uuuuuuuuuuuuuuuuuuuuuuuuu");
    }

    public static void login(String name, String password,String code) {
        User usr = User.find("byName", name).first();
        if (usr == null) {
            flash.error("用户不存在");
            index();
        }
        if (!usr.password.equals(password)) {
            flash.error("密码错误");
            index();
        }
        String codeInCache = (String)Cache.get(session.getId());
        if (!codeInCache.equals(code)) {
        	  flash.error("输入验证码错误");
            index();
        }
        Cache.delete(session.getId());
        session.put("usr", usr.id);
        show(usr.getId());
    }

    public static void dealRegister(String name, String password, String repassword) {
        if (!password.equals(repassword)) {
            flash.error("两次输入密码不相同");
            register();
        }
        if (name.isEmpty()) {
            flash.error("用户名不能为空");
            register();
        }
        long usrCnt = User.count("name = ? ", name);
        if (usrCnt != 0) {
            flash.error("用户名已存在");
            register();
        }
        User usr = new User(name, password);
        usr.save();
        show(usr.getId());
    }
    
    public static void register() {
        render("Application/register.html");
    }

    public static void show(long id) {
            System.out.println(getUser().name);
            System.out.println(getUser().background);
        User usr = getUser();
        List<MBlog> allMBlog = new ArrayList<MBlog>();
        //List<Follow> Followings = Follow.find(null, params).fetch();
        for (User u : usr.getFollowing()) {
            List<MBlog> followingMBlog = MBlog.find("byAuthor", u).fetch();
            for (MBlog p : followingMBlog) {
                if(!u.equals(usr)){
                    allMBlog.add(p);
                }
            }
        }
        List<MBlog> myMBlog = MBlog.find("byAuthor", usr).fetch();
        for (MBlog p : myMBlog) {
            allMBlog.add(p);
        }

        /*for (MBlog p : allMBlog) {
            System.out.println(p.content);
            System.out.println(p.author);
        }*/
        
        if(allMBlog.size()!=0){
                Collections.sort(allMBlog, new Comparator<MBlog>(){
                    public int compare(MBlog p1, MBlog p2){
                            return p2.id.compareTo(p1.id);
                    }
                });
        }
        renderArgs.put("allMBlog", allMBlog);
        render(usr);
    }

    
    public static void publish(String content, File img, List<String> ats, Long originPostId) throws WeiboException {

            

        User usr = getUser();
        MBlog post = new MBlog(usr, content, new Date());
        post.save();  
        if (img != null) {
            //System.out.println("postID:"+post.id);
            //System.out.println(img.getName());
            try {

                String filePath = "public/images/postImgFolder";
                File myFilePath = new File(filePath);
                if (!myFilePath.exists()) {//创建头像图片目录
                    myFilePath.mkdir();
                    System.out.println("************" + myFilePath.getAbsolutePath() + "\n\n");
                }
                //String dest = myFilePath.getAbsolutePath() + "/" + usr.name+attachment.toString().substring(attachment.toString().lastIndexOf("."), attachment.toString().length());//以用户名作为头像图片名
                String dest = myFilePath.getAbsolutePath() + "/" + post.id + img.toString().substring(img.toString().lastIndexOf("."), img.toString().length());
                FileInputStream in = new FileInputStream(img.getPath());//保存头像图片
                File file = new File(dest);
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileOutputStream out = new FileOutputStream(file);
                int c;
                byte buffer[] = new byte[1024];
                while ((c = in.read(buffer)) != -1) {
                    for (int i = 0; i < c; i++) {
                        out.write(buffer[i]);
                    }
                }
                post.image = "/public/images/postImgFolder/" + file.getName();
                in.close();
                out.close();

            } catch (Exception e) {
                System.out.println("file error ***************************");
                e.printStackTrace();
            }
        }
          
        if(originPostId!=null){

            MBlog origin = MBlog.findById(originPostId);
            post.originId = originPostId;
            origin.forwardCnt ++;
            origin.save();
            post.save();
            new At(post, origin.author).save();
            Notify notice = Notify.getNotifyById( origin.author.id );
            notice.publishAtEvent(post);
        }else{
            post.save();
        }
        //通知被@到的用户
        if(ats!=null){
            for(String at:ats){
                    User usrAted =  User.find("byName",at).first();  //找到被@的用户
                    if(usrAted==null) continue;
                    Notify notice = Notify.getNotifyById( usrAted.id );
                    notice.publishAtEvent(post);
                    new At(post, usrAted).save(); //保存@信息
            }
        }
      
        usr.postCnt++;
        usr.save();
     
        //通知粉丝有新微博    
        for(User follower: usr.getFollowers()){

                if(!follower.name.equals(usr.name)){
                    System.out.println(follower.name);     
                    
                    Notify inform = Notify.getNotifyById( follower.id );
                    inform.publishMBlogEvent( post );
                }
        } 
        //通知自己有新微博
        Notify myInform = Notify.getNotifyById( getUserId() );
        myInform.publishMBlogEvent( post );


        //与新浪微博同步 
        try{
                if (usr.weiboToken != null) {
                    Timeline timeline = new Timeline();
                    timeline.setToken(usr.weiboToken);
                    timeline.UpdateStatus(content);
                }
        }
        catch(Exception e){
            System.out.println("some mistake occurs when  synchronizing with weibo");
        }
    }
    public static void getNewMBlogs(){
            Notify myNotify = Notify.getNotifyById( getUserId() );
            List<IndexedEvent<MBlog>> newMBlogs = await(myNotify.getMBlogEvents(0));
            myNotify.deleteMBlogEvents();
            renderArgs.put("usr",getUser());
            render("Application/newMBlog.html", newMBlogs);
    }
    
    public static void getAtMe(){
         Notify myNotify = Notify.getNotifyById( getUserId() );
         List<IndexedEvent<MBlog>> ats = await( myNotify.getAtEvents());
         myNotify.deleteAtEvents();
        
         renderJSON(ats);
    } 

    public static void deleteMBlog(long postId) {
        //应验证所删除微博是否用户所有
        User usr = getUser();
        usr.postCnt--;
        usr.save();
        MBlog post = MBlog.findById(postId);        
        System.out.print(post.content);
        List<At> ats = At.find("byPost",post).fetch();
        for(At at: ats){
                at.delete();
        }//删除该微博@到的信息，避免删除异常
        System.out.print("OKKKK");
        //post.delete();      
        post.delete();
    }

    public static void logout() {
        session.put("usr", null);
        index();
    }
    public static void deleteComment(long commentId,long postId){
        MBlog pst = MBlog.findById(postId);
        Comments comment = Comments.findById(commentId);
        comment.delete();
        pst.commentCnt--;
        pst.save();
    }

    public static void comment() {
        List<Comments> comments = Comments.find("byToUsr",getUser()).fetch();
        renderArgs.put("usr", getUser());
        render(comments);
    }

    public static void followers() {
        renderArgs.put("usr", getUser());
        render();
    }

    public static void followings() {
        renderArgs.put("usr", getUser());
        render();
    }

    public static void myposts() {
        renderArgs.put("usr", getUser());
        render();
    }

    public static void myat() {
        renderArgs.put("usr", getUser());
        renderArgs.put("title","@到我的");
        renderArgs.put("posts", getUser().getAtMe());
        render("Application/myat.html");
    }

    //与新浪微博同步
    public static void syncRequest() throws WeiboException {
        Oauth oauth = new Oauth();
        String oauthURL = oauth.authorize("code");
        System.out.println(oauthURL);
        redirect(oauthURL);
    }
    public static void syncCancel(){
        currentUser.weiboToken = null;
        currentUser.save(); 
        index();
    }

    public static void callback(String code) throws WeiboException {
        Oauth oauth = new Oauth();
        AccessToken accessToken = oauth.getAccessTokenByCode(code);
        User usr = getUser();
        usr.weiboToken = accessToken.getAccessToken();
        usr.save();
        //System.out.println(usr.weiboToken);
        index();

    }

    public static void getComment(long postId){
        MBlog pst = MBlog.findById(postId);

        List<Comments> comments =  Comments.find("byPost",pst).fetch();
        render("Application/mycomments.html",comments);
    }

    public static void makeComment(long postId, String content){

        System.out.println("hereasdasfasdf");
        System.out.println("here"+postId);

        MBlog pst = MBlog.findById(postId);
        
        System.out.println("here"+pst.author.name);
        User usr = getUser();
        new Comments(pst,usr,content).save();
        pst.commentCnt++;
        pst.save();

       // 通知微博作者有人评论
        Notify notice = Notify.getNotifyById( pst.author.id );
        notice.publishCommentEvent(pst);

    }
    
    public static void getCommentNotice(){
         Notify myNotify = Notify.getNotifyById( getUserId() );
         List<IndexedEvent<MBlog>> comments = await( myNotify.getCommemtEvents());
         myNotify.deleteCommentEvents();
         renderJSON(comments);
    }

    public static void saveImg(String content, File img) {
        System.out.println(content + img.toString());
        System.out.println(img.getName());
        try {
            User usr = getUser();
            String filePath = "public/images/postImgFolder";
            File myFilePath = new File(filePath);
            if (!myFilePath.exists()) {//创建头像图片目录
                myFilePath.mkdir();
                System.out.println("************" + myFilePath.getAbsolutePath() + "\n\n");
            }
            //String dest = myFilePath.getAbsolutePath() + "/" + usr.name+attachment.toString().substring(attachment.toString().lastIndexOf("."), attachment.toString().length());//以用户名作为头像图片名
            String dest = myFilePath.getAbsolutePath() + "/" + usr.name + img.toString().substring(img.toString().lastIndexOf("."), img.toString().length());
            FileInputStream in = new FileInputStream(img.getPath());//保存头像图片
            File file = new File(dest);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            int c;
            byte buffer[] = new byte[1024];
            while ((c = in.read(buffer)) != -1) {
                for (int i = 0; i < c; i++) {
                    out.write(buffer[i]);
                }
            }
            in.close();
            out.close();

        } catch (Exception e) {
            System.out.println("file error ***************************");
            e.printStackTrace();
        }
    }

    public static void forword(){
    } 
    
    //登陆验证码生成
    public static void captcha() {
    Images.Captcha captcha = Images.captcha();
    String code = captcha.getText("#E4EAFD").toLowerCase();
    Cache.set(session.getId(),code);
    renderBinary(captcha);
}
}
